<?php

namespace App\Console\Commands;

use App\Winged\Auth\Api\Auth;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Redis;

class Tenant extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tenant:init 
                            {username} 
                            {password} 
                            {tenant_id} 
                            {services}
                            {admin_default_url}'; // link "user,system,config"

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'init tenant_config example: php artisan tenant:init wingedcareadmin 000000  cd3hospital \'system,user,evaluation\' \'/admin/evaluation/index/#/patients\'';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $username = $this->argument('username') ;
        $password = $this->argument('password') ;
        $admin_default_url = $this->argument('admin_default_url');

        $servicecs = explode(',' , $this->argument('services')) ;
//        $admin_default_url = $this->argument('admin_default_url') ;

        $this->tenant_id = $this->argument('tenant_id') ;

        if(is_null($username) || is_null($password) || is_null($servicecs) || is_null($this->tenant_id) || is_null($admin_default_url))
        {
            $this->error('arguments can`t be null') ;
            exit(0) ;
        }
        $token = json_decode($this->post('auth/login' , json_encode(['username' => $username ,'password' => $password]), 'body'), true);

        if($realtoken = data_get($token, 'access_token')) {
            $this->token = $realtoken;
        }
        else{
            $this->error("login error" . json_encode($token));
            exit(0);
        }
        $this->updateConfig(['services' => json_encode($servicecs) ,'admin_default_url' => $admin_default_url]);
    }


    protected function updateConfig( $update ){
        $uri = 'uaa/config/update_config';
        $config = [
            'config_prefix' => $this->tenant_id ,
            'configs' => [
                'tenant_id' => $this->tenant_id ,
                'tenant_uuid' => $this->tenant_id ,
            ],
        ];
        $config ['configs'] = array_merge($config['configs'] ,$update);
        $res = $this->post($uri ,['data' => json_encode($config)]);

        $this->info($res);
    }


    public function post($url ,$params, $postOption = "form_params")
    {
        $channels = config('winged.backend.channels');
        $config = config('winged.backend.http');
        $config = $channels [$config['channel']] ;
        $client = new Client([
            'base_uri'        => $config['host'],
            'connect_timeout' => $config['connect_timeout'],
            'timeout'         => $config['request_timeout'],
            'verify'          => $config['ssl_verify'],
            'http_errors'     => false,
            'debug'           => false
        ]);
        $options ['headers'] = [] ;
        if($postOption == 'body') {
            $options ['headers']['Content-Type'] = "application/json";
        }
        $options[$postOption] = $params;
        $options['headers'] = array_merge($options['headers'] ,$this->getHeader()) ;
        $response = $client->request('POST', $url, $options);
        $body = $response->getBody()->getContents();
        $status = $response->getStatusCode();
        if($status >= 200 && $status < 300)
        {
            return $body ;
        }
        else{
            $this->error('server response an error status of:' . $status);
            exit(0);
        }
    }


    protected $tenant_id ;

    protected $token ;

    public function getHeader()
    {
        $header = [
            'tenant_id' => $this->tenant_id,
            'PLATFORM' => '0',
        ];

        if($this->token != null)
        {
            $header ['ACCESS_TOKEN'] = "x" ;
            $header ['Authorization'] = "Bearer " . $this->token ;
        }


        return $header ;
    }
    
}















